package com.udhtu.ii.lab1;

import static com.udhtu.ii.lab1.Function.*;

/**
 * метод половинного деления(бисекции)
 */
public class BisectionMethod {
    private double epsilon;
    private double left;
    private double right;
    private int count;

    BisectionMethod() {
        epsilon = Function.EPSILON;
        left = Function.LEFT;
        right = Function.RIGHT;
    }

    private double goldSequenceMethod(int goal) {
        double x1, x2, f1, f2;
        count=0;
        left = LEFT;
        right = RIGHT;
        while (Math.abs(right - left) > epsilon) {
            count++;
            x1 = (left + right - epsilon / 2) / 2;
            x2 = (left + right + epsilon / 2) / 2;
            f1 = function(x1);
            f2 = function(x2);

            if (f1 >= f2 * goal)
                left = x1;
            else right = x2;
        }

        return function((left + right) / 2);
    }

    public void compute() {

        System.out.println("Метод половинного деления:");
        System.out.println("min=" + goldSequenceMethod(MIN));
        System.out.println("max=" + goldSequenceMethod(MAX));
        System.out.println("count="+count);
    }
}
